
import { ab2hex, int2hex, hexToArrayBuffer} from './index.js';
// TODO searchDevice 调用

const appStore = getApp()

// 校验权限 微信版
const checkScope = () => {
  return new Promise((resolve, reject) => {
    console.log('getSetting')
    uni.getSetting({
      success: function (res) {
        console.log('getSetting success', res)
        if (!res.authSetting['scope.bluetooth']) {
          uni.authorize({
            scope: 'scope.bluetooth',
            success: () => {
              if (!res.authSetting['scope.userLocation']) {
                uni.authorize({
                  scope: 'scope.userLocation',
                  success: () => {
                    resolve()
                  },
				  fail: (e) => {
					  console.log('authorize failed', e)
				      reject()
				  }
                })
              } else {
                resolve()
              }
            },
            fail: (e) => {
              console.log('authorize failed', e)
			  reject()
            }
          })
        } else {
          if (!res.authSetting['scope.userLocation']) {
            uni.authorize({
              scope: 'scope.userLocation',
              success: () => {
                resolve()
              },
              fail: (e) => {
                console.log('authorize failed', e)
				reject()
              }
            })
          } else {
            resolve()
          }
        }
      },
      fail: (e) => {
        console.log(e, 'getSetting failed')
        reject(e)
      }
    })
  })
}


/**
 * 检查蓝牙权限
 */
export const checkScopeHandel = () => {
  return new Promise((resolve, reject) => {
    checkScope().then(_ => {
      console.log('checkScope')
      resolve()
    }).catch(() => {
      uni.showModal({
        title: '请开启蓝牙权限!',
        showCancel: false
      })
      reject()
    })
  })
}

/**
 * 搜索设备并连接（需要交互的页面load后需要调佣这个初始化链接）
 * @param mac { mac:需要链接的mac地址 }
 * @param isAutoConnect 是否搜索到自动连接
 */
export const searchDevice = ({ mac, isAutoConnect = true }) => {
  return new Promise(async (resolve, reject) => {
    await checkScopeHandel();
    // 如果已经链接过
    if (appStore.globalData.deviceBleInfo?.deviceId && appStore.globalData.deviceBleInfo?.isConnect && appStore.globalData.deviceBleInfo?.mac == mac) {
      resolve()
      return connectDevice(appStore.globalData.deviceBleInfo?.deviceId, appStore.globalData.deviceBleInfo?.mac)
    }
	if(isAutoConnect) {
		//自动连接的话显示loading
		uni.showLoading({
		  title: '正在搜索设备...',
		  mask: false
		})
	}
    uni.openBluetoothAdapter({
      success: () => {
        setTimeout(() => {
          uni.startBluetoothDevicesDiscovery({
            allowDuplicatesKey: true,
            success: (res) => {
              console.log(res, "startBluetoothDevicesDiscovery");
              uni.onBluetoothDeviceFound((data) => {

                data.devices.forEach(item => {
                  if (item.name.includes('iEMC-')) {
                    console.log(data, "onBluetoothDeviceFound找到设备了");
                    let suffix = int2hex(item.name.substring(5)).toUpperCase()
                    let macSuffix = mac.substring(12 - suffix.length)
                    console.log(suffix, macSuffix, "suffix,macSuffix")
                    if (suffix === macSuffix) {
                      console.log(item, '匹配到设备')
					  uni.stopBluetoothDevicesDiscovery()
					  // 存储蓝牙设备ID
					  appStore.globalData.deviceBleInfo.deviceId = item.deviceId
					  appStore.globalData.deviceBleInfo.mac = mac
					  appStore.globalData.deviceBleInfo.isConnect = false
					  // 如果是自动连接则连接
					  if(isAutoConnect) {
						  // 链接设备
						  connectDevice(item.deviceId, mac).then(() => {
							resolve(data.devices)
						  }).catch((e) => {
							reject(e)
						  })
					  }
                    }
                  }
                })
              })
            },
            fail: (err) => {
              console.log(err);
              if (err.errno == 1500104) {
                uni.showModal({
                  title: "连接失败，频繁操作请重试！",
                  showCancel: false,
                  success () {
					  uni.navigateBack()
					  uni.hideLoading()
                  }
                })
              }
            }
          })
        }, 300)
      },
      fail: (err) => {
        console.log('----初始化蓝牙失败----', err);
        if (err.errCode == 10001) {
          uni.showModal({
            title: "请打开蓝牙",
            showCancel: false,
            success () {
            }
          })
        }
		reject(err)
      }
    })
  })
}

/**
 * 断开设备
 */
const disconnectDevice = (deviceId) => {
  return new Promise((resolve, reject) => {
	uni.hideLoading()
    uni.closeBLEConnection({
      deviceId,
      success (res) {
        console.log(res)
        console.log(deviceId + '： 断开连接成功！');
        resolve()
      },
      fail (err) {
        console.log('断开连接失败！：');
        console.log(err);
        resolve()
      }
    })
  })
}

/**
 * 连接设备
 */
export const connectDevice = (deviceId, mac) => {
  return new Promise(async (resolve, reject) => {
    // 断开之前链接的设备
	if(appStore.globalData.deviceBleInfo?.deviceId && appStore.globalData.deviceBleInfo?.isConnect && appStore.globalData.deviceBleInfo?.mac != mac) {
      await disconnectDevice(appStore.globalData.deviceBleInfo?.deviceId)
	}
    uni.showLoading({
      title: "连接中..."
    })
    uni.createBLEConnection({
      deviceId,
      timeout: 1000 * (appStore.globalData?.deviceConTime || 15),
      success (res) {
        console.log(res);
        console.log(deviceId + ': --链接成功--');
		// 设置最大单元
		uni.setBLEMTU({
			deviceId:deviceId,
			mtu: 400,
			success() {
				console.log('设置最大单元成功！');
			}
		})
        uni.hideLoading()
        getBLEDeviceServices(deviceId, mac).then(() => {
          resolve(deviceId)
        }).catch((e) => {
          reject(e)
        })
      },
      fail (e) {
        console.log(e);
        if (e.errMsg.split(":")[2] == 'already connect') {
          // 已经链接
          console.log('已经链接');
          uni.hideLoading()
		  // 已经链接 但是没有存到相关数据 重新存
		  if(!appStore.globalData.deviceBleInfo?.deviceId && !appStore.globalData.deviceBleInfo?.serviceId) {
			 getBLEDeviceServices(deviceId, mac).then(() => {
			   resolve(deviceId)
			 }).catch((e) => {
			   reject(e)
			 })
		  }else {
			  resolve(deviceId)
		  }
        } else if (e.errCode == 10012) {
		uni.hideLoading()
          uni.showModal({
            title: "连接超时，请重新连接！",
            showCancel: false,
            success () {
            }
          })
		  reject()
        } else {
		  uni.showModal({
			title: "连接失败，errCode" + e.errCode,
			showCancel: false,
			success () {
			}
		  })
          reject()
        }
      }
    })
  })
}

/**
 * 获取蓝牙设备所有特征值
 */
const getBLEDeviceServices = (deviceId, mac) => {
  return new Promise((resolve, reject) => {
    uni.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        console.log(res, "getBLEDeviceServices");
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            getBLEDeviceCharacteristics(deviceId, res.services[i].uuid, mac).then(() => {
              resolve(res.services)
            }).catch((e) => {
              reject(e)
            })
            return
          }
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}



/**
 * 获取蓝牙设备某个服务中所有特征值(characteristic)
 */
const getBLEDeviceCharacteristics = (deviceId, serviceId, mac) => {
  return new Promise((reslove, reject) => {
    uni.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        if (!res.characteristics.length) {
          console.log('characteristics长度为0');
        } else {
          console.log('characteristics长度为' + res.characteristics.length);
        }
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i]
          console.log(item);
          if (item.properties.read) {
            uni.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
          }
          if (item.properties.notify || item.properties.indicate) {
            uni.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
            })
          }
          if (item.properties.write) {
            console.log('write', {
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            });

            // 存储蓝牙设备信息
			appStore.globalData.deviceBleInfo = {
				deviceId,
				serviceId,
				characteristicId: item.uuid,
				mac,
				isConnect: true//是否已经链接
			}
            reslove()
          }
        }
      },
      fail (res) {
        console.error('getBLEDeviceCharacteristics', res)
        console.log(res);
        reject(res)
      }
    })
  })
}


/**
 * 监听设备回复数据
 */
export function onBLECharacteristicValueChange () {
  return new Promise((resolve, reject) => {
    uni.offBLECharacteristicValueChange()//先关闭监听
    uni.onBLECharacteristicValueChange((res) => {
      console.log("onBLECharacteristicValueChange开启监听");

      const hexStr = ab2hex(res.value)//回复的16进制数据
      const byteArray = new Uint8Array(res.value);//回复的字节数组

      console.log("characteristic: " + res);
      console.log(hexStr, "hexStr")
      console.log(byteArray, "byteArray");
      resolve({
        hexStr,
        byteArray
      })
    })
  })
}